/**
 * This file is part of Too-OneBee.
 *
 * Too-OneBee is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Too-OneBee is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Too-OneBee.  If not, see <http://www.gnu.org/licenses/>.
 */
package net.dataforte.tooonebee;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Script console JMX tree JNDI tree Server information Application information
 * Session information Request information JDBC/SQL queries
 * 
 * @author tst
 * 
 */
public class TooOneBeeServlet extends HttpServlet {
	String scriptEngineName = "javascript";
	private ClassLoader contextClassLoader;
	Map<String, ServiceIntrospector> handlers;
	List<Menu> menus;

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		contextClassLoader = Thread.currentThread().getContextClassLoader();

		handlers = new HashMap<String, ServiceIntrospector>();
		menus = new ArrayList<Menu>();
		
		List<? extends ServiceIntrospector> services = ServiceFinder.findServices(ServiceIntrospector.class);
		for (ServiceIntrospector service : services) {
			handlers.put(service.getRequestPath(), service);
			menus.addAll(service.getMenuEntries());
		}
		
	
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		String pathInfo = req.getPathInfo();
		if (pathInfo == null) {
			pathInfo = "";
		}

		if (pathInfo.startsWith("/")) {
			pathInfo = pathInfo.substring(1);
		}
		int slash = pathInfo.indexOf('/');
		if (slash > 0) {
			pathInfo = pathInfo.substring(0, slash);
		}

		ServiceIntrospector handler = handlers.get(pathInfo);

		if (handler != null) {
			try {
				handler.handleRequest(this, req, res);
			} catch (Exception e) {

			}
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		String resource = req.getPathInfo();
		if (resource == null || resource.equals("/")) {
			resource = "/index.html";
		} else if (resource.contains("..")) {
			throw new ServletException("Invalid resource " + resource);
		}
		if("/menu".equals(resource)) {
			res.setContentType("text/plain");
			JSON.mirror(res.getWriter(), menus);
			return;
		}
		String mimeType = MimeMap.getMimeTypeFromExtension(resource);
		if (mimeType == null) {
			throw new ServletException("Invalid resource " + resource);
		}
		res.setContentType(mimeType);
		try {
			resource = "net/dataforte/tooonebee/resources" + resource;
			InputStream is = new BufferedInputStream(contextClassLoader.getResourceAsStream(resource));
			ServletOutputStream os = res.getOutputStream();
			StreamUtils.copyStream(is, os);
			is.close();
		} catch (IOException e) {
			System.err.println("Error reading resource " + resource);
			throw e;
		}
		return;
	}

}
